<template>
  <div class="header">
    <a-dropdown placement="bottomRight" :disabled="user.id === ''">
      <a-tooltip v-if="user.id === ''" placement="topRight">
        <template #title>Login for more rights</template>
        <a-avatar class="avatar" shape="square" @click="gotoLgoin">
          <template #icon>
            <UserOutlined />
          </template>
        </a-avatar>
      </a-tooltip>
      <a-avatar
        v-else-if="user.userAvatar != ''"
        class="avatar"
        shape="square"
        :src="user.userAvatar"
      ></a-avatar>
      <a-avatar
        v-else
        class="avatar"
        shape="square"
        style="background-color: #1890ff"
        >{{ user.userName.substr(0, 1) }}
      </a-avatar>

      <DownOutlined />
      <template #overlay>
        <a-menu @click="handleMenuClick">
          <a-menu-item key="0">
            <UserOutlined />
            个人信息
          </a-menu-item>
          <a-menu-item key="1">
            <EditOutlined />
            创作中心
          </a-menu-item>
          <a-menu-item key="4">
            <SyncOutlined spin />
            修改密码
          </a-menu-item>
          <a-menu-divider />
          <a-menu-item key="3" style="color: #b03d3d">
            <LogoutOutlined />
            退出登录
          </a-menu-item>
        </a-menu>
      </template>
    </a-dropdown>
  </div>
  <div>
    <a-modal
      v-model:visible="visible"
      title="修改密码"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
    >
      <a-form layout="vertical"
        :model="formState"
        name="basic"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
      >
        <a-form-item
          label="旧密码"
          name="userPassword"
          :rules="[{ required: true, message: 'Please input your userPassword!' }]"
        >
          <a-input-password v-model:value="formState.userPassword" />
        </a-form-item>

        <a-form-item
          label="新密码"
          name="newPassword"
          :rules="[{ required: true, message: 'Please input your newPassword!' }]"
        >
          <a-input-password v-model:value="formState.newPassword" />
        </a-form-item>
        <a-form-item
          label="确认密码"
          name="checkPassword"
          :rules="[{ required: true, message: 'Please input your checkPassword!' }]"
        >
          <a-input-password v-model:value="formState.checkPassword" />
        </a-form-item>
<!--        <a-form-item :wrapper-col="{ offset: 8, span: 16 }">-->
<!--          <a-button type="primary" html-type="submit">Submit</a-button>-->
<!--        </a-form-item>-->
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { createVNode, onBeforeMount, ref } from "vue";
import {
  DownOutlined,
  EditOutlined,
  ExclamationCircleOutlined,
  LogoutOutlined,
  SyncOutlined,
  UserOutlined,
} from "@ant-design/icons-vue";
import myAxios from "@/plugins/myAxios";
import { MenuProps, message, Modal } from "ant-design-vue";
import router from "@/router";

function formatDateTime(date: string): string {
  const datetime = new Date(date);
  const year = datetime.getFullYear();
  const month = String(datetime.getMonth() + 1).padStart(2, "0");
  const day = String(datetime.getDate()).padStart(2, "0");
  const hour = String(datetime.getHours()).padStart(2, "0");
  const minute = String(datetime.getMinutes()).padStart(2, "0");
  const format = `${year}-${month}-${day} ${hour}:${minute}`;
  return format;
}

const handleMenuClick: MenuProps["onClick"] = (e) => {
  switch (e.key) {
    case "0":
      gotoPersonal();
      // showModal()
      // console.log(user);
      break;
    case "1":
      router.push("/md");
      break;
    case "3":
      logoutModal();
      break;
    case "4":
      showModal();
      break;
    default:
      console.log("onerror");
  }
};

const logoutModal = () => {
  Modal.confirm({
    content: "确定要退出登录吗？",
    icon: createVNode(ExclamationCircleOutlined),
    onOk() {
      return new Promise((resolve, reject) => {
        setTimeout(Math.random() > 0.5 ? resolve : reject, 500);
      }).catch(() => logout());
    },
    cancelText: "取消",
    onCancel() {
      Modal.destroyAll();
    },
  });
};

const gotoPersonal = () => {
  router.push(`/personal/${user.value.id}`);
};

const logout = () => {
  myAxios.post("user/logout").then((res: any) => {
    if (res == true) {
      message.success("登出成功");
      location.reload();
    } else {
      message.error(res);
    }
  });
};
const gotoLgoin = () => {
  router.push("/login");
};
let user = ref({
  id: "",
  userName: "",
  userAvatar: "",
  userProfile: "",
  userRole: "",
  createTime: "",
  updateTime: "",
});

const getLoginUser = async () => {
  await myAxios.get("user/get/login").then((res: any) => {
    // console.log(res, "_____________Hander");
    if (res !== null) {
      user.value = res;
      localStorage.setItem("isLogin", "true");
      localStorage.setItem("id", res.id);
      localStorage.setItem("userRole", res.userRole);
    } else {
      user.value.id = "";
      localStorage.setItem("isLogin", "false");
      localStorage.removeItem("id");
      localStorage.removeItem("userRole");
    }
  });
};
onBeforeMount(() => {
  getLoginUser();
});
// if (document.title === "aggregatiensearch") {
//   document.title = "聚合搜索-创作";
// }

const visible = ref<boolean>(false);

const showModal = () => {
  visible.value = true;
};

const handleOk = (e: MouseEvent) => {
  confirmLoading.value = true;
  myAxios.post("user/update/passwd", formState).then((res: any) => {
    console.log(res);
    if (res != null) {
      message.success("密码修改成功");
      setTimeout(() => {
        visible.value = false;
        confirmLoading.value = false;
      }, 2000);
    } else {
      setTimeout(() => {
        confirmLoading.value = false;
      }, 1000);
    }
  });
};

const open = ref<boolean>(true);
const confirmLoading = ref<boolean>(false);

interface FormState {
  userPassword: string;
  newPassword: string;
  checkPassword: string;
  remember: boolean;
}
import { reactive } from 'vue';

const formState = reactive<FormState>({
  userPassword: '',
  newPassword: '',
  checkPassword: '',
  remember: true,
});


</script>

<style scoped>
.header {
  height: 50px;
  width: 50px;
  /*  width: 120px;*/
  float: right;
  display: flex;
  flex-wrap: nowrap;
  justify-content: center;
  align-items: center;
}
</style>
